package com.softserve.crazymachine.configurator;

import java.io.IOException;
import java.util.*;

import javax.swing.JOptionPane;

/**
 * Class, that represent singleton-based object, which is used to configure
 * server properties
 * 
 * @author Taras Krutiak
 */
public class Configurator {

	private static Configurator instance;
	private Map<String, Object> configPages; // List of web-server
												// configurations
	private String settingsDirectory;
	private boolean modified;
	private boolean status;

	{
		configPages = null;
		settingsDirectory = "config.xml";
		modified = false;
		status = true;
	}

	private Configurator() {
	}

	/**
	 * Returns the Singleton-based Configurator object
	 * 
	 * @return Configurator class object
	 */
	public synchronized static Configurator getInstance() {
		if (instance == null) {
			instance = new Configurator();
		}
		return instance;
	}

	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

	public void saveConfigurations() {

		if (configPages != null && modified) {

			XmlConverter.whriteToXml(configPages, settingsDirectory);
		}

	}

	public void loadConfigurations() {

		configPages = XmlConverter.readFromXml(settingsDirectory);
		System.out.println(configPages);

	}

	public Map<String, Object> getConfigPages() {
		return configPages;
	}

	public String getByKey(String key) throws IOException {

		return getByKey(configPages, key);
	}

	public String getByKey(String key, String innerkey) throws IOException {
		Object value = configPages.get(key);
		if (!(value instanceof Map) || (value == null)) {
			throw new IOException();
		}
		Map map = (HashMap) value;

		return getByKey(map, innerkey);
	}

	private String getByKey(Map<String, Object> map, String key)
			throws IOException {
		Object value = map.get(key);
		if (!(value instanceof String) || (value == null)) {
			throw new IOException();
		}
		return value.toString();
	}

	public static void main(String... args) {
		Configurator a = Configurator.getInstance();
		a.loadConfigurations();
		try {
			System.out.println(a.getByKey("file-type", "html"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
